<template>
  <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
    <a-form-model :model="stationData">
      <a-form-item
        label="油站编号"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
      >
        <a-input v-model="stationData.code_id"/>
      </a-form-item>
      <a-form-item
        label="油站名称"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
      >
        <a-input v-model="stationData.title"/>
      </a-form-item>
      <a-form-item
        label="地区"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
      >
        <div class="grid">
          <a-input placeholder="省份" v-model="stationData.province"/>
          <a-input placeholder="城市" v-model="stationData.city"/>
          <a-input placeholder="地区" v-model="stationData.area"/>
        </div>
      </a-form-item>
      <a-form-item
        label="详细地址"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
      >
        <a-textarea rows="3" v-model="stationData.address"/>
      </a-form-item>
      <a-form-item
        label="所售油品"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
        :required="false"
      >
        <a-checkbox-group v-model="checkedList" :options="plainOptions" />
      </a-form-item>
      <a-form-item
        label="国标价"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 3}"
      >
        <a-input v-model="stationData.nation_price" suffix="元"/>
      </a-form-item>
      <a-form-item
        label="柴油原价"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 3}"
      >
        <a-input v-model="stationData.original_price" suffix="元"/>
      </a-form-item>
      <a-form-item
        label="柴油现价"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 3}"
      >
        <a-input v-model="stationData.now_price" suffix="元"/>
      </a-form-item>
      <a-form-item
        label="经度"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
      >
        <a-input v-model="stationData.longitude"/>
      </a-form-item>
      <a-form-item
        label="纬度"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
      >
        <a-input v-model="stationData.latitude"/>
      </a-form-item>
      <a-form-item
        label="营业时间"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
      >
        <a-time-picker 
          placeholder="起始时间" 
          @change="onChangeStart"
          :default-value="moment(business_start_time, 'HH:mm')" 
          format="HH:mm" />
        <span> - </span>
        <a-time-picker 
          placeholder="截止时间" 
          @change="onChangeEnd"
          :default-value="moment(business_end_time, 'HH:mm')" 
          format="HH:mm" />
      </a-form-item>
      <a-form-item
        label="电话"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
      >
        <a-input v-model="stationData.tel" />
      </a-form-item>
      <a-form-item
        label="营业状态"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
      >
        <a-switch 
          default-checked 
          checked-children="开" 
          un-checked-children="关" 
          v-model="business_state" />
      </a-form-item>
      <a-form-item
        label="店铺图片"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 5}"
      >
        <a-upload
          name="image"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :before-upload="beforeUpload"
          :headers="headers"
          action="/api/image/upload"
          @change="handleChange"
        >
          <img v-if="stationData.shop_image" :src="$staticUrl + stationData.shop_image" alt="avatar" class="shop_image"/>
          <div v-else>
            <a-icon :type="imgLoading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">
              上传图片
            </div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item
        label="备注"
        :labelCol="{span: 7}"
        :wrapperCol="{span: 10}"
      >
        <a-textarea rows="3" v-model="stationData.desc"/>
      </a-form-item>
      <a-form-item style="margin-top: 24px" :wrapperCol="{span: 10, offset: 7}">
        <a-button type="primary" v-if="isEdit" @click="edit">修改</a-button>
        <a-button type="primary" v-else @click="create">确定</a-button>
        <a-button style="margin-left: 10px" @click="cancel">返回</a-button>
      </a-form-item>
    </a-form-model>
  </a-card>
</template>

<script>
import { mapGetters } from 'vuex'
import * as Api from '@/services/index'
import moment from 'moment';
const plainOptions = ['0#', '092', '095', '098']

// function getBase64(img, callback) {
//   const reader = new FileReader();
//   reader.addEventListener('load', () => callback(reader.result));
//   reader.readAsDataURL(img);
// }

export default {
  name: 'BasicForm',
  data () {
    return {
      checkedList: [],
      plainOptions,
      value: 1,
      business_state: true,
      imageUrl: '',
      imgLoading: '',
      shop_image: '',
      business_start_time: '00:00',
      business_end_time: '23:59',
    }
  },
  computed: {
    ...mapGetters('account', ['stationData', 'token']),
    isEdit() {
      return this.stationData.id ? true : false
    },
    headers() {
      return {
        'Authorization': 'Bearer ' + this.token,
        'X-Requested-With': 'XMLHttpRequest' 
      }
    }
  },
  created() {
    // 编辑
    if (this.isEdit) {
      this.checkedList = this.stationData.sell_type.split(';')
      this.business_state = !!this.stationData.business_state
      this.business_start_time = this.stationData.business_start_time
      this.business_end_time = this.stationData.business_end_time
    } else {
      this.checkedList = plainOptions
    }
  },
  methods: {
    moment,
    onChangeStart(time, timeString) {
      this.business_start_time = timeString
    },
    onChangeEnd(time, timeString) {
      this.business_end_time = timeString
    },
    create() {
      let params = {
        ...this.stationData,
        // shop_image: this.shop_image,
        sell_type: this.checkedList.join(';'),
        business_state: this.business_state ? '1' : '2',
        business_start_time: this.business_start_time,
        business_end_time: this.business_end_time,
      }
      Api.CreateStation(params).then(res => {
        this.$message.success(res.message);
        this.$router.push('/stationlist')
      })
    },
    edit() {
      let params = {
        ...this.stationData,
        // shop_image: this.shop_image,
        sell_type: this.checkedList.join(';'),
        business_state: this.business_state ? '1' : '2',
        business_start_time: this.business_start_time,
        business_end_time: this.business_end_time,
      }
      Api.EditStation(params).then(res => {
        this.$message.success(res.message);
        this.$router.push('/stationlist')
      })
    },
    cancel() {
      this.$router.push('/stationlist')
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.imgLoading = true;
        return;
      }
      if (info.file.status === 'done') {
        // 如果已经有图片则先删除图片
        if (this.stationData.shop_image) {
          this.handleRemove()
        }
        this.stationData.shop_image = info.file.response.data.url
        // 如果是编辑的，图片上传成功立刻保存
        this.isEdit && this.saveImage()
      }
    },
    // 删除图片
    handleRemove() {
      Api.DeleteImg({image: this.stationData.shop_image})
    },
    // 保存图片
    saveImage() {
      let params = {
        id: this.stationData.id,
        shop_image: this.stationData.shop_image,
      }
      Api.EditStation(params)
    },
    beforeUpload(file) {
      console.log(file);
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
  },
}
</script>

<style scoped lang="less">
.grid{
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 20px;
}
.shop_image{
  max-width: 200px;
}
</style>
